package com.example.applets.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.applets.entity.Cart;
import com.example.applets.entity.CartVo;
import com.example.applets.service.impl.CartServiceImpl;
import com.example.applets.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author 云烟成雨丶
 * @since 2020-10-16
 */
@Controller
@RequestMapping("/Kshop/cart")
public class CartController {
    @Autowired
    private CartServiceImpl cartService;

    @RequestMapping("/collection")
    @ResponseBody
    //收藏商品
    public AjaxResult collection(@RequestParam("prodid") long prodId, @RequestParam("num") int num, @RequestParam("userid") long userId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("prodid", prodId);
        wrapper.eq("userid", userId);
        if (cartService.getOne(wrapper) != null)
            return AjaxResult.error("你已经添加,切勿重复!");
        Cart cart = new Cart();
        cart.setProdid(prodId);
        cart.setUserid(userId);
        cart.setNum(num);
        if (!cartService.save(cart))
            return AjaxResult.error("收藏失败!");
        return AjaxResult.success("收藏成功!");
    }

    @RequestMapping("/page")
    @ResponseBody
    //收藏商品
    public AjaxResult selectPage(@RequestParam("userId") long userid) {
        List<CartVo> list = cartService.selectWithPro(userid);
        if (list.size() == 0)
            return AjaxResult.error("暂无收藏!");
        return AjaxResult.success(list);
    }

    @RequestMapping("/updateNum")
    @ResponseBody
    //收藏商品
    public AjaxResult updateNum(@RequestParam("cartId") long id, @RequestParam("num") int num) {
        Cart cart = cartService.getById(id);
        cart.setNum(num);
        if (!cartService.updateById(cart))
            return AjaxResult.error("修改失败!");
        return AjaxResult.success("修改成功!");
    }

    @RequestMapping("/delete")
    @ResponseBody
    //收藏商品
    public AjaxResult deleteCart(@RequestParam("cartId") long id) {
        if (!cartService.removeById(id))
            return AjaxResult.error("删除失败!");
        return AjaxResult.success("删除成功!");
    }

    @RequestMapping("/empty")
    @ResponseBody
    //收藏商品
    public AjaxResult emptyCart(@RequestParam("userId") long userId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("userid", userId);
        if (!cartService.remove(wrapper))
            return AjaxResult.error("清空失败!");
        return AjaxResult.success("清空成功!");
    }


}

